package lew.bing.novels;

import java.io.Closeable;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Created by 刘国兵 on 2019/8/18.
 *
 * @author 刘国兵
 */
public  class TxtWriter implements NovelWriter {

    private String parentPath;

    private String name;

    private boolean split;

    private FileWriter fileWriter;

    private int maxIdx;

    public TxtWriter(String parentPath, String name, boolean split, int maxIdx) throws IOException {
        this.parentPath = parentPath;
        this.name = name;
        this.split = split;
        this.maxIdx = maxIdx;
        if (!split) {
            File file = new File(parentPath + "/" + name + ".txt");
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            fileWriter = new FileWriter(file);
        }
    }

    @Override
    public void write(Novel novel) throws IOException {
        if (novel == null  || novel.getContent() == null) {
            return;
        }
        FileWriter fileWriter = fileWriter(novel);
        if (fileWriter != null) {
            try {
                if (!split) {
                    fileWriter.write("第"+(novel.getIdx()+1) +"章: " +novel.getTitle()+"\r\n");
                }
                fileWriter.write(novel.getContent());
                fileWriter.write("\r\n");
            } finally {
                if (split) {
                    fileWriter.close();
                }
            }
        }
    }

    private String idxString(int idx) {
        int i = 0;
        int maxIdx = this.maxIdx;
        while (maxIdx != 0) {
            i ++;
            maxIdx = maxIdx / 10;
        }
        return String.format("chapter.%0"+i+"d", idx);
    }

    private FileWriter fileWriter(Novel novel) throws IOException {
        if (split) {
            if (novel == null || novel.getTitle() == null) {
                return null;
            }
            File file = new File(parentPath + "/" + name + "/" + idxString(novel.getIdx()) + novel.getTitle() + ".txt");
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            return new FileWriter(file);
        }
        return fileWriter;
    }


    public void setSplit(boolean split) {
        this.split = split;
    }

    @Override
    public void close() throws IOException {
        if (fileWriter != null) {
            fileWriter.close();
        }
    }
}
